package com.ychen.goodscenter.service.biz;


import com.ychen.framework.utils.SnowFlakeUtils;
import com.ychen.goodscenter.dao.GoodsInfoMapper;
import com.ychen.goodscenter.dao.OrderInfoMapper;
import com.ychen.goodscenter.entity.GoodsInfo;
import com.ychen.goodscenter.entity.OrderInfo;
import com.ychen.goodscenter.enums.OrderStatusEnum;
import com.ychen.goodscenter.vo.req.SubmitOrderReq;
import com.ychen.usercenter.api.AccountFacade;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

@Service
public class OrderBizService {
    @Autowired
    private GoodsInfoMapper goodsInfoMapper;

    @Autowired
    private AccountFacade accountFacade;

    @Autowired
    private OrderInfoMapper orderInfoMapper;

    // 减少库存并创建订单
    @Transactional(rollbackFor = {Exception.class})
    public OrderInfo reduceStockAndCreateOrder(SubmitOrderReq req) {
        //向数据库查询库存,并加锁
        GoodsInfo goodsInfo = goodsInfoMapper.selectByPrimaryKey(req.getGoodsId(), true);
        // 检查库存
        if (goodsInfo.getStock() < req.getTradeNumber()) {
            throw new RuntimeException("stock not enough");
        }
        // 扣减库存
        goodsInfoMapper.reduceStock(req.getGoodsId(), req.getTradeNumber());
        // 创建订单
        OrderInfo orderInfo = buildOrderInfo(req, goodsInfo);
        orderInfoMapper.insert(orderInfo);
        return orderInfo;
    }

    // 回滚库存并且更新订单
    @Transactional(rollbackFor = {Exception.class})
    public void rollbackStockAndUpdateOrder(OrderInfo orderInfo) {
        // 回滚库存
        goodsInfoMapper.rollbackStock(orderInfo.getGoodsId(), orderInfo.getTradeNumber());
        // 创建订单
        orderInfo.setOrderStatus(OrderStatusEnum.PAYMENT_FAILED.getCode());
        orderInfoMapper.updateOrderStatusByPrimaryKey(orderInfo.getId(), orderInfo.getOrderStatus());
    }

    private OrderInfo buildOrderInfo(SubmitOrderReq req, GoodsInfo goodsInfo) {
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setId(req.getOrderId());
        orderInfo.setGoodsId(req.getGoodsId());
        orderInfo.setGoodsName(goodsInfo.getGoodsName());
        orderInfo.setTradeNumber(req.getTradeNumber());
        orderInfo.setSellerId(goodsInfo.getSellerId());
        orderInfo.setBuyerId(req.getUserId());
        orderInfo.setOrderAmount(goodsInfo.getPrice().multiply(BigDecimal.valueOf(req.getTradeNumber())));
        orderInfo.setOrderStatus(OrderStatusEnum.PAYING.getCode());
        return orderInfo;
    }
}
